package com.dawnling.mpchartdemo.ui;

import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;

import com.dawnling.mpchartdemo.R;
import com.dawnling.mpchartdemo.bean.IncomeBean;
import com.dawnling.mpchartdemo.bean.LineChartBean;
import com.dawnling.mpchartdemo.utils.DateUtil;
import com.dawnling.mpchartdemo.utils.LocalJsonAnalyzeUtil;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.ChartTouchListener;
import com.github.mikephil.charting.listener.OnChartGestureListener;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;

import java.util.ArrayList;
import java.util.List;

/**
 * 曲线图只需要步骤1、2、3即可,搜索todo可配置曲线折现
 * 其他都是折线图
 */
public class KeytopNeedActivity extends AppCompatActivity implements OnChartValueSelectedListener {

    /**
     * 曲线图1
     */
    private LineChart lineChart1;
    private LineChartManager lineChartManager1;
    private List<IncomeBean> incomeBeanList;//个人收益
    private LineChartBean lineChartBean;
    /**
     * 曲线图1结束
     */
    private LineChart chart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_keytop_need);

        initData();
        initView();
    }

    /**
     * 曲线图2
     */
    private void initData() {
        //获取数据 曲线图
        lineChartBean = LocalJsonAnalyzeUtil.JsonToObject(this, "line_chart.json", LineChartBean.class);
        incomeBeanList = lineChartBean.getGRID0().getResult().getClientAccumulativeRate();
    }

    private void initView() {
        /**
         * 曲线图3
         */
        lineChart1 = findViewById(R.id.lineChart);
        lineChartManager1 = new LineChartManager(lineChart1);
        //展示图表
        lineChartManager1.showLineChart(incomeBeanList, "新增客户", getResources().getColor(R.color.blue));
        //设置曲线填充色 以及 MarkerView
        Drawable drawable = getResources().getDrawable(R.drawable.fade_blue);
        lineChartManager1.setChartFillDrawable(drawable);
        lineChartManager1.setMarkerView(this);
        /**
         * 曲线图3结束
         */

        /**
         * 折线图开始
         */
        chart = findViewById(R.id.chart1);
        // background color
        chart.setBackgroundColor(Color.WHITE);
        // disable description text
        chart.getDescription().setEnabled(false);
        // enable touch gestures
        chart.setTouchEnabled(true);
        // set listeners
        chart.setOnChartValueSelectedListener(this);
        chart.setDrawGridBackground(false);
        //支持滑动弹窗
        chart.setDragEnabled(true);
        //不支持拖拽放大缩小
        chart.setScaleEnabled(false);
        chart.setPinchZoom(true);
        chart.setNoDataText("暂无数据");

        XAxis xAxis;
        {   // // X-Axis Style // //
            xAxis = chart.getXAxis();
            // vertical grid lines
            xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置x轴的显示位置
            //设置竖线的显示样式为虚线
            //lineLength控制虚线段的长度
            //spaceLength控制线之间的空间
            xAxis.enableGridDashedLine(10f, 10f, 0f);
            //自加：
//        xAxis.setAxisMinimum(0f);//设置x轴的最小值
//        xAxis.setAxisMaximum(10f);//设置最大值
            //自加：去掉X轴网格背景
            xAxis.setDrawGridLines(false);
            //自加：设置是否一个格子显示一条数据，如果不设置这个属性，就会导致X轴数据重复并且错乱的问题
            xAxis.setGranularity(1f);
        }

        YAxis yAxis;
        {   // // Y-Axis Style // //
            yAxis = chart.getAxisLeft();
            // disable dual axis (only use LEFT axis)
            chart.getAxisRight().setEnabled(false);
            // horizontal grid lines
            yAxis.enableGridDashedLine(10f, 10f, 0f);
            // axis range
            yAxis.setAxisMaximum(200f);
            yAxis.setAxisMinimum(-50f);
            //去掉Y轴网格背景
            yAxis.setDrawGridLines(false);
        }

        // create marker to display box when values are selected 弹出自定义窗口
//        MyMarkerView mv = new MyMarkerView(this, R.layout.custom_marker_view);
//        // Set the marker to the chart
//        mv.setChartView(chart);
//        chart.setMarker(mv);
        // 弹出自定义窗口
        LineChartMarkView mv = new LineChartMarkView(this, xAxis.getValueFormatter());
        mv.setChartView(chart);
        chart.setMarker(mv);
        chart.invalidate();

        // draw points over time
        chart.animateX(1500);
        // get the legend (only possible after setting data)
        Legend l = chart.getLegend();
        // draw legend entries as lines
        l.setForm(Legend.LegendForm.LINE);
        //判断滑动后，且没有单击的时候MarkView自动消失
        chart.setOnChartGestureListener(new OnChartGestureListener() {
            @Override  public void onChartGestureEnd(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {
                if (lastPerformedGesture != ChartTouchListener.ChartGesture.SINGLE_TAP)
                    chart.highlightValues(null);
            }
            @Override public void onChartGestureStart(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {}
            @Override public void onChartLongPressed(MotionEvent me) {}
            @Override public void onChartDoubleTapped(MotionEvent me) {}
            @Override public void onChartSingleTapped(MotionEvent me) {}
            @Override public void onChartFling(MotionEvent me1, MotionEvent me2, float velocityX, float velocityY) {}
            @Override public void onChartScale(MotionEvent me, float scaleX, float scaleY) {}
            @Override public void onChartTranslate(MotionEvent me, float dX, float dY) {} });

        //初始化数据
        setData(7, 180);
        //重新设置x轴数据 不设置默认0-6
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                String tradeDate = incomeBeanList.get((int) value % incomeBeanList.size()).getTradeDate();
                return DateUtil.formatDateToMD(tradeDate);
            }
        });
    }

    private void setData(int count, float range) {
        ArrayList<Entry> values = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            float val = (float) (Math.random() * range) - 30;
            values.add(new Entry(i, val, getResources().getDrawable(R.drawable.star)));
        }
        LineDataSet set1;
        if (chart.getData() != null &&
                chart.getData().getDataSetCount() > 0) {
            set1 = (LineDataSet) chart.getData().getDataSetByIndex(0);
            set1.setValues(values);
            set1.notifyDataSetChanged();
            chart.getData().notifyDataChanged();
            chart.notifyDataSetChanged();
        } else {
            // create a dataset and give it a type
            set1 = new LineDataSet(values, "折线图");
            set1.setDrawIcons(false);
            // draw dashed line 将选择线绘制为虚线
//            set1.enableDashedLine(10f, 5f, 0f);
            // black lines and points
            set1.setColor(Color.BLACK);
            set1.setCircleColor(Color.BLACK);
            // line thickness and point size
            set1.setLineWidth(1f);
            set1.setCircleRadius(3f);
            // draw points as solid circles
            set1.setDrawCircleHole(false);
            // customize legend entry
            set1.setFormLineWidth(1f);
            set1.setFormLineDashEffect(new DashPathEffect(new float[]{10f, 5f}, 0f));
            set1.setFormSize(15.f);
            // draw selection line as dashed 将选择线绘制为虚线的大小
            set1.enableDashedHighlightLine(10f, 5f, 0f);
            // text size of values
            set1.setValueTextSize(9f);
            // set the filled area  是否折线区域内染色
//            set1.setDrawFilled(false);
//            set1.setFillFormatter(new IFillFormatter() {
//                @Override
//                public float getFillLinePosition(ILineDataSet dataSet, LineDataProvider dataProvider) {
//                    return chart.getAxisLeft().getAxisMinimum();
//                }
//            });
//            // set color of filled area 设置图标下方渐变色
//            if (Utils.getSDKInt() >= 18) {
//                // drawables only supported on api level 18 and above
//                Drawable drawable = ContextCompat.getDrawable(this, R.drawable.fade_red);
//                set1.setFillDrawable(drawable);
//            } else {
//                set1.setFillColor(Color.BLACK);
//            }
            ArrayList<ILineDataSet> dataSets = new ArrayList<>();
            dataSets.add(set1); // add the data sets
            // create a data object with the data sets
            LineData data = new LineData(dataSets);
            // set data
            chart.setData(data);
        }
    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {
        Log.i("Entry selected", e.toString());
        Log.i("LOW HIGH", "low: " + chart.getLowestVisibleX() + ", high: " + chart.getHighestVisibleX());
        Log.i("MIN MAX", "xMin: " + chart.getXChartMin() + ", xMax: " + chart.getXChartMax() + ", yMin: " + chart.getYChartMin() + ", yMax: " + chart.getYChartMax());
    }

    @Override
    public void onNothingSelected() {
        Log.i("Nothing selected", "Nothing selected.");
    }
}
